import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from "@/utils/auth"

const instance = axios.create(
  {
    baseURL: '/bio_platform',
    timeout: 50000,
    headers: { "Content-Type": "application/json;charset=utf-8" },
    // paramsSerializer: (params) => qs.stringify(params),
  }
)

// 请求拦截
instance.interceptors.request.use(
  (config) => {
    const accessToken = getToken()
    // 如果 Authorization 设置为 no-auth，则不携带 Token，用于登录、刷新 Token 等接口
    if (config.headers.Authorization !== "no-auth" && accessToken) {
      config.headers.token = accessToken
    } else {
      delete config.headers.token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// 响应拦截
instance.interceptors.response.use(
  async (response) => {
    // console.log(response, 'successRes')
    const { status, statusText, data } = response
    if (!status || !statusText) {
      ElMessage.error('请求失败，请重试!')
      return Promise.reject(response)
    }
    if (![200, 204].includes(status)) {
      ElMessage.error(statusText)
      return Promise.reject(response)
    }
    if (data.code !== 200) {
      ElMessage.error(data.msg)
      return Promise.reject(response)
    }
    return response.data
  },
  (error) => {
    // do something
    console.log(error, 'errorResponse')
    const { response: { statusText } } = error
    ElMessage.error(statusText)
    return Promise.reject(error)
  }
)

export default instance
